import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';

class TimeSelect extends StatefulWidget {
  const TimeSelect({Key? key}) : super(key: key);

  @override
  _TimeSelectState createState() => _TimeSelectState();
}

class _TimeSelectState extends State<TimeSelect> {
// 初始化开始时间
// 初始化结束时间
  String _selectedDate = '';
  String _dateCount = '';
  String _range = '';
  String _rangeCount = '';
  String StartTime = "";
  String EndTime = "";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("选择日期"),
      ),
      body: Container(
          color: Colors.white,
          child: Column(
            children: [
              // 日期范围
              SelectDate(),
              // 确定按钮
              ConfrimBtn(context),
            ],
          )),
    );
  }

  // 选择日期范围
  Widget SelectDate() {
    return Container(
        child: SfDateRangePicker(
      onSelectionChanged: _onSelectionChanged,
      selectionMode: DateRangePickerSelectionMode.range,
      initialSelectedRange: PickerDateRange(
          DateTime.now().subtract(const Duration(days: 4)),
          DateTime.now().add(const Duration(days: 3))),
    ));
  }

// 确定按钮
  Widget ConfrimBtn(context) {
    return Container(
      child: MaterialButton(
        onPressed: () {
          Back(context);
        },
        child: Text(
          "确定",
          style: TextStyle(color: Colors.white),
        ),
        color: Colors.blue,
      ),
    );
  }

  //选择日期范围事件
  void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) {
    //  formatDate(DateTime.now(), [yyyy, "年", mm, "月", dd])
    setState(() {
      if (args.value is PickerDateRange) {
        StartTime = formatDate(args.value.startDate, [yyyy, "-", mm, "-", dd]);
        EndTime = formatDate(args.value.endDate ?? args.value.startDate,
            [yyyy, "-", mm, "-", dd]);

        // _range = '${DateFormat('dd/MM/yyyy').format(args.value.startDate)} -'
        //     // ignore: lines_longer_than_80_chars
        //     ' ${DateFormat('dd/MM/yyyy').format(args.value.endDate ?? args.value.startDate)}';
      } else if (args.value is DateTime) {
        _selectedDate = args.value.toString();
      } else if (args.value is List<DateTime>) {
        _dateCount = args.value.length.toString();
      } else {
        _rangeCount = args.value.length.toString();
      }
    });
  }

  // 返回页面事件
  Future<void> Back(context) async {
    Map map = new Map();
    map['StartTime'] = StartTime;
    map['EndTime'] = EndTime;
    // 返回上页面
    Navigator.pop(context, map);
  }
}
